package com.gopay.common.util.xml.utils.validator.tools;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.gopay.common.util.xml.utils.XmlBeansUtils;
import com.gopay.common.util.xml.utils.validator.BaseValidator;
import com.gopay.common.util.xml.utils.validator.DefaultCompareToValidator;
import com.gopay.common.util.xml.utils.validator.DefaultLengthValidator;
import com.gopay.common.util.xml.utils.validator.DefaultPatternValidator;
import com.gopay.common.util.xml.utils.validator.DefaultRequiredValidator;
import com.gopay.common.util.xml.utils.validator.DefaultValueLengthValidator;
import com.gopay.common.util.xml.xmlutils.message.Validator;
import com.gopay.common.util.xml.xmlutils.message.xml.vo.BFNode;
import com.gopay.common.util.xml.xmlutils.message.xml.vo.Field;

/**
 * 
 * @author liujy
 *
 */
public class ValidatorTools {
	
	/**  */
    private final static String DEFAULT_PACKAGE_NAME = "com.gopay.common.util.xml.utils.validator";
    
    /** 系统默认的校验是否为空类 */
    private final static String DEFAULT_REQURIED_VALIDATOR = DEFAULT_PACKAGE_NAME + "DefaultRequiredValidator";
    /** 系统默认的长度校验类 */
    private final static String DEFAULT_LENGTH_VALIDATOR = DEFAULT_PACKAGE_NAME + "DefaultLengthValidator";
    /** 系统默认的字符串长度校验类 */
    private final static String DEFAULT_VALUELENGTH_VALIDATOR = DEFAULT_PACKAGE_NAME + "DefaultValueLengthValidator";
    /** 系统默认的正则表达式校验类 */
    private final static String DEFAULT_PATTERN_VALIDATOR = DEFAULT_PACKAGE_NAME + "DefaultPatternValidator";
    /** 系统默认的CompareTo校验类 */
    private final static String DEFAULT_COMPARE_TO_VALIDATOR = DEFAULT_PACKAGE_NAME + "DefaultCompareToValidator";
    
    /** 校验器集 */
    private final static Map<String, BaseValidator> validators = new HashMap<String, BaseValidator>();
    
    private ValidatorTools(){
    	
    }
    
    static{
    	validators.put(DEFAULT_REQURIED_VALIDATOR, new DefaultRequiredValidator());
    	validators.put(DEFAULT_LENGTH_VALIDATOR, new DefaultLengthValidator());
    	validators.put(DEFAULT_VALUELENGTH_VALIDATOR, new DefaultValueLengthValidator());
    	validators.put(DEFAULT_PATTERN_VALIDATOR, new DefaultPatternValidator());
    	validators.put(DEFAULT_COMPARE_TO_VALIDATOR, new DefaultCompareToValidator());
    }

    /**
     * 
     * @param field
     */
    public static void validator(BFNode node, Object data) throws Exception{
       
    	if (node == null) {
            return;
        }
    	
        if(!(node instanceof Field)){
        	return;
        }
        
        Field field = (Field)node;
        
        List<Validator> validators = field.getValidators();
        if (validators == null || validators.size() == 0) {
            return;
        }
        String combinationField = null;
        String combinationValue = null;
        Validator validator = null;
        for (Iterator<Validator> it = validators.iterator(); it.hasNext();) {
            validator = it.next();
            combinationField = validator.getCombinationField();
            if (null != combinationField && !"".equals(combinationField)) {
                XmlBeansUtils.getPropertyObject(data, combinationField);
                validator.setCombinationValue(combinationValue);
            }
            BaseValidator baseValidator = getInstance(validator);
            boolean flag = baseValidator.execute(validator, XmlBeansUtils.getPropertyObject(data, field.getName()));
            if (false == flag) {
            	StringBuilder b = new StringBuilder();
            	b.append("errorCode: ").append(validator.getErrorCode());
            	b.append("|message: ").append(validator.getMessage());
                throw new Exception(b.toString());
            }
        }
        return;
    }

    /**
     * 获取验证类的实例
     * 
     * @param validatorClass
     * @return
     */
    private static BaseValidator getInstance(Validator validator) {
    	
    	String validatorClass = getValidatorClass(validator);
    	
        BaseValidator baseValidator = validators.get(validatorClass);
        if(baseValidator != null){
        	return baseValidator;
        }
    	try {
            Class<?> clas = Class.forName(validatorClass);
            baseValidator = (BaseValidator) clas.newInstance();
        } catch (Exception e) {
            throw new RuntimeException("create ValidatorInstance error: " + validatorClass, e);
        }
    	validators.put(validatorClass, baseValidator);
        return baseValidator;
    }

    /**
     * 获取验证类的名称
     * 
     * @param validator
     * @return
     */
    private static String getValidatorClass(Validator validator) {
        if (validator == null) {
            return null;
        }
        if (StringUtils.isBlank(validator.getType())) {
            if (validator.isRequired()) {
                validator.setType(DEFAULT_REQURIED_VALIDATOR);
            } else if (StringUtils.isNotBlank(validator.getPattern())) {
                validator.setType(DEFAULT_PATTERN_VALIDATOR);
            } else if (StringUtils.isNotBlank(validator.getCompareTo())) {
                validator.setType(DEFAULT_COMPARE_TO_VALIDATOR);
            } else if (StringUtils.isNotBlank(validator.getMinLength())
                    || StringUtils.isNotBlank(validator.getMaxLength())) {
                validator.setType(DEFAULT_LENGTH_VALIDATOR);
            } else if (StringUtils.isNotBlank(validator.getMinValue())
                    || StringUtils.isNotBlank(validator.getMaxValue())) {
                validator.setType(DEFAULT_VALUELENGTH_VALIDATOR);
            }
        }
        return validator.getType();
    }
}
